import { useUserStore } from '@/store/user'
import Request, { type HttpMethod, type HttpRequestConfig } from 'luch-request'

export const baseURL = 'https://consult-api.itheima.net'
const service = new Request({
  baseURL,
  timeout: 20000,
  custom: {
    // 自定义参数
    isShowLoading: true,
  },
})

// 白名单
const whiteList = ['/login', '/login/password', '/code']

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    if (config.custom?.isShowLoading) {
      uni.showLoading({
        title: '加载中...',
        mask: true,
      })
    }
    // 携带token
    const store = useUserStore()
    if (store.token && !whiteList.includes(config.url!)) {
      config.header!.Authorization = `Bearer ${store.token}`
    }
    return config
  },
  (config) => {
    return Promise.reject(config)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (res) => {
    if (res.config.custom?.isShowLoading) {
      uni.hideLoading()
    }
    if (res.data.code !== 10000) {
      uni.showToast({
        title: res.data.message,
        icon: 'none',
      })
      return Promise.reject(res.data)
    }

    // 剥离数据
    return res.data.data
  },
  (error) => {
    if (error.config.custom?.isShowLoading) {
      uni.hideLoading()
    }
    if (error.data.code === 401) {
      uni.showToast({
        title: error.data.message,
        icon: 'none',
      })
      const store = useUserStore()
      store.removeToken()
      // 跳转登录页,不保留当前页面
      uni.reLaunch({
        url: '/pages/login/login',
      })
    }
    return Promise.reject(error)
  }
)

// interface ServiceResponse<T> {
//   code: number
//   message: string
//   data: T
// }

const request = <T>(
  url: string,
  method: HttpMethod = 'GET',
  params?: object,
  // 配置项 可以覆盖默认配置,本项目主要用于改变custom的值
  config?: HttpRequestConfig
) => {
  return service.request<T, T>({
    url,
    method,
    [method === 'GET' ? 'params' : 'data']: params,
    ...config,
  })
}

export { request,service }
